// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

import Common from "../Common";
import UserLevelItem from "./UserLevelItem";

const {ccclass, property} = cc._decorator;

@ccclass
export default class UserLevelPage extends Common {

    @property(cc.Node)
    backBtn: cc.Node = null;

    @property(cc.Node)
    contentNode: cc.Node = null;

    protected rowItem: cc.Prefab

    protected colItem: cc.Prefab

    protected colLength = 3


    protected watch = {
        shopGoods: async (goods) => {
            const l = goods.length
            if (l === 0) {
                return;
            }
            let index = 0, subGroupLength = this.colLength;
            let data = [];

            while (index < l) {
                data.push(goods.slice(index, index += subGroupLength));
            }
            for (let item of data) {
                const rowNode = await this.attachRow()
                for (let i = 0; i < subGroupLength; i++) {
                    const colNode = cc.instantiate(await this.getColItem())
                    const col = item[i]
                    const colItem = colNode.getComponent(UserLevelItem)
                    if (typeof col === 'undefined') {
                        colItem.setIsEmpty(true)
                    } else {
                        colItem.setIsEmpty(false)
                        colItem.setLevel(col.id)
                        colItem.setTitle(col.name || '')
                        colItem.setNumber(col._user_counts || 0)
                        colItem.setStatus(col._current_status)
                    }
                    rowNode.addChild(colNode)
                }
            }
            console.log(data)
        }
    }

    start() {
        this.backBtn.on(cc.Node.EventType.TOUCH_START, () => {
            this.onBtnClick()
            cc.director.loadScene('profile')
        }, this) // 点击返回首页按钮


        this.initShopGoodLists()
    }

    initShopGoodLists() {
        this.http.get('goods/lists', {with_user_counts: 1}).then(async ({data}) => {
            this._data.shopGoods = data;
        }).catch(console.log)
    }

    async attachRow() {
        const rowNode = cc.instantiate(await this.getRowItem())
        this.contentNode.addChild(rowNode)
        return rowNode
    }


    async getRowItem() {
        if (!this.rowItem) {
            this.rowItem = await this.getPrefab('level/row')
        }
        return this.rowItem
    }

    async getColItem() {
        if (!this.colItem) {
            this.colItem = await this.getPrefab('level/item')
        }
        return this.colItem
    }

}
